package org.jeecg.modules.wangyue.interceptor.filter;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.wangyue.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * token拦截器
 */
@Component
public class TokenFilter implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isValidToken = false;
        String tokenId = request.getHeader("tokenId");
        String token = request.getHeader("token");

        String time = DateUtil.getTimeStr("yyyy-MM-dd HH:mm:ss");
        //如果在redis中，key为tokenId对应的value，与token值相等，则允许调用接口
        if(oConvertUtils.isNotEmpty(token) && oConvertUtils.isNotEmpty(tokenId) && token.equals(redisTemplate.opsForValue().get("token_" + tokenId))){
            System.out.println("(" + time + ")用户id(" + tokenId + ")_Token(" + token + ")：有效 | " + request.getServletPath());
            isValidToken = true;
        }else{ //不相等，说明token失效
            System.out.println("(" + time + ")用户id(" + tokenId + ")_Token(" + token + ")：失效 | " + request.getServletPath());
            isValidToken = false;
//            isValidToken = true;

//            response.setContentType("application/json;charset=UTF-8");
//            response.setCharacterEncoding("UTF-8");
//            response.setStatus(401);
//            response.getWriter().write("Token失效，请重新登录!");

            String jsonObjectStr = JSONObject.toJSONString(Result.error(401, "Token失效，请重新登录!"));
            returnJson(response, jsonObjectStr);
        }
        return isValidToken;
    }

    //给前端输出json的方法
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
